package com.zy.imagineCommunity.controller;

import com.alibaba.fastjson.JSONObject;
import com.zy.imagineCommunity.entity.*;
import com.zy.imagineCommunity.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class BlogManagementController {

    @Autowired
    BlogService blogService;

    @GetMapping("/blogManagement")
    public String getBlogManagement() {
        return "/BlogManagement";
    }

    @ResponseBody
    @PostMapping("/toBlogManagement")
    public JSONObject blogManagement(int page) {
        JSONObject jsonObject = new JSONObject();

        //通过id查询用户
        Page<BlogTextTwo> pageText = blogService.queryBlogPageNoAndPageSize(page, 10);

        for (BlogTextTwo blogTextTwo : pageText.getItems()) {
            System.out.println(blogTextTwo);
        }

        jsonObject.put("code", 0);
        jsonObject.put("count", pageText.getPageCountTotal());
        jsonObject.put("data", pageText.getItems());

        return jsonObject;
    }

    @GetMapping("/blogManagementByType/{type}")
    public String getBlogManagementByType(@PathVariable("type") int type, Model model) {
        model.addAttribute("type", type);
        return "/BlogManagementByType";
    }

    @ResponseBody
    @PostMapping("/toBlogManagementByType/{type}")
    public JSONObject blogManagement(@PathVariable("type") int type, int page) {
        JSONObject jsonObject = new JSONObject();

        Page<BlogTextTwo> pageText = blogService.queryBlogTextTwoByTypeAndBeginAndPageSize(type, page, 10);

        for (BlogTextTwo blogTextTwo : pageText.getItems()) {
            System.out.println(blogTextTwo);
        }

        jsonObject.put("code", 0);
        jsonObject.put("count", pageText.getPageCountTotal());
        jsonObject.put("data", pageText.getItems());

        return jsonObject;
    }

    /**
     * 删除blog
     *
     * @param id
     */
    @ResponseBody
    @PostMapping("/deleteAdminBlog")
    public void deleteAdminBlog(int id) {
        blogService.deleteBlogById(id);
    }

    /**
     * 批量删除blog
     *
     * @param idList
     */
    @ResponseBody
    @PostMapping("/deleteBlogList")
    public void deleteBlogList(String idList) {

        String[] id = idList.split(",");

        for (int i = 0; i < id.length; i++) {
            if (!"".equals(id[i])) {
                int idInt = Integer.parseInt(id[i]);
                blogService.deleteBlogById(idInt);
            }
        }

    }

}
